//
// Created by user on 2022/3/3.
//
#include <vector>
#include <unordered_map>
#include <queue>
using namespace std;
//小顶堆

static bool cmp(pair<int, int>&m, pair<int, int> &n){
    return m.second > n.second;//升序
}

vector<int> topKFrequent(vector<int>& nums, int k) {
    unordered_map<int, int> map;
    for (int num:nums){
        map[num]++;
    }

    //小顶堆
    priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(&cmp)> pq(cmp);
    for(auto & [num,cnt]:map){
        pq.emplace(num, cnt);
        if (pq.size() > k) {
            pq.pop();
        }
    }

    vector<int> res;
    while (!pq.empty()) {
        res.emplace_back(pq.top().first);
        pq.pop();
    }
    return res;
}
